package com.example.smart.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import com.example.lib.extend.dip2px
import com.example.lib.extend.getDeviceWidth
import com.example.lib.extend.getResourceColor
import com.example.lib.extend.sp2px
import com.example.smart.R
import com.example.smart.utils.NumberUtils
import androidx.core.content.withStyledAttributes

/**
 * 图表选择日期弹窗顶部周视图
 */
class WeekView @JvmOverloads constructor(context: Context, attributes: AttributeSet? = null, defaultStyle: Int = 0) :
    View(context, attributes, defaultStyle) {

    private var boxWidth = 0f //宽度
    private val boxHeight = getContext().dip2px(50f)//高度
    private var margin = 0f//高度
    private val windowWidth = getDeviceWidth(getContext()) - context.dip2px(40f)
    private var viewWidth = 0f
    private var rowSize = 7 //列数

    //星期文字画笔
    private val textWeekPaint by lazy {
        Paint().also {
            it.color = getContext().getResourceColor(com.example.lib.R.color.black_0a0b35)
            it.flags = Paint.ANTI_ALIAS_FLAG
            it.textSize = getContext().sp2px(14).toFloat()
        }
    }

    private val weekRect by lazy {
        Rect()
    }

    init {
        context.withStyledAttributes(attributes, R.styleable.WeekView) {
            margin = getDimension(R.styleable.WeekView_margin_left_right, 0f)
            viewWidth = windowWidth.toFloat() - margin - margin
        }
        initTextWidth()
    }

    private fun initTextWidth() {
        boxWidth = viewWidth / 7
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        setMeasuredDimension(windowWidth, boxHeight)
    }

    override fun onDraw(canvas: Canvas) {
        for (j in 0 until rowSize) {
            val translateWeek = NumberUtils.translateWeek(j + 1)
            textWeekPaint.getTextBounds(translateWeek, 0, translateWeek.length, weekRect)
            canvas.drawText(translateWeek,
                boxWidth * j + getTextRightPadding() + margin,
                boxHeight.toFloat() - getTextTopPadding(),
                textWeekPaint)
        }
    }

    private fun getTextTopPadding(): Float {
        return ((boxHeight - weekRect.height()) / 2).toFloat()
    }


    private fun getTextRightPadding(): Float {
        return (boxWidth - weekRect.width()) / 2
    }
}
